<template>
  <div class="page">
    <t-nav-bar
        title="报修记录"
        left-text="返回"
        left-arrow
        @click-left="handleBack"
    />
    <div class="content">
      <h1>报修记录</h1>

      <h2 style="font-size: 18px; color: #333; margin-top: 22px; margin-bottom: 10px;">申请中</h2>
      <div v-if="sortedPendingRecords.length > 0" class="records-container">
        <div v-for="record in sortedPendingRecords" :key="record.failureRepairId" class="record-card">
          <h3 class="card-title">{{ record.title }}</h3>
          <div class="card-content">
            <p><span>用户编号:</span> {{ record.userNo }}</p>
            <p><span>姓名:</span> {{ record.fullName }}</p>
            <p><span>类型:</span> {{ record.type }}</p>
            <p><span>报修时间:</span> {{ record.repairTime }}</p>
            <p><span>联系电话:</span> {{ record.contactNumber }}</p>
            <p><span>维修地址:</span> {{ record.repairAddress }}</p>
            <p><span>故障描述:</span> {{ record.faultDescription }}</p>
            <p><span>报修状态:</span> {{ record.repairStatus }}</p>
            <p><span>创建时间:</span> {{ formatDate(record.createTime) }}</p>
            <p><span>更新时间:</span> {{ formatDate(record.updateTime) }}</p>
          </div>
          <div class="card-actions">
            <el-button type="primary" size="small" @click="editRecord(record)">修改</el-button>
<!--            <el-button type="danger" size="small" @click="deleteRecord(record.failureRepairId)">删除</el-button>-->
          </div>
        </div>
      </div>
      <div v-else class="no-records">暂无申请中的记录</div>

      <h2 style="font-size: 18px; color: #333; margin-top: 22px; margin-bottom: 10px;">已审批</h2>
      <div v-if="sortedApprovedRecords.length > 0" class="records-container">
        <div v-for="record in sortedApprovedRecords" :key="record.failureRepairId" class="record-card">
          <h3 class="card-title">{{ record.title }}</h3>
          <div class="card-content">
            <p><span>用户编号:</span> {{ record.userNo }}</p>
            <p><span>姓名:</span> {{ record.fullName }}</p>
            <p><span>类型:</span> {{ record.type }}</p>
            <p><span>报修时间:</span> {{ record.repairTime }}</p>
            <p><span>联系电话:</span> {{ record.contactNumber }}</p>
            <p><span>维修地址:</span> {{ record.repairAddress }}</p>
            <p><span>故障描述:</span> {{ record.faultDescription }}</p>
            <p><span>报修状态:</span> {{ record.repairStatus }}</p>
            <p><span>创建时间:</span> {{ formatDate(record.createTime) }}</p>
            <p><span>更新时间:</span> {{ formatDate(record.updateTime) }}</p>
          </div>
        </div>
      </div>
      <div v-else class="no-records">暂无已审批的记录</div>
    </div>
    <div class="fixed-bottom-bar">
      <el-button type="primary" @click="returnToMenu">返回</el-button>
    </div>

    <!-- 修改记录的弹窗 -->
    <el-dialog v-model="dialogVisible" title="修改报修记录" width="90%" class="edit-dialog">
      <el-form :model="editForm" label-width="100px" class="edit-form">
        <el-form-item label="标题">
          <el-input v-model="editForm.title" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="editForm.type" style="width: 100%;">
            <el-option label="电气" value="电气" />
            <el-option label="管道" value="管道" />
            <el-option label="木工" value="木工" />
            <el-option label="其它" value="其它" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="editForm.contactNumber" />
        </el-form-item>
        <el-form-item label="维修地址">
          <el-input v-model="editForm.repairAddress" />
        </el-form-item>
        <el-form-item label="故障描述">
          <el-input v-model="editForm.faultDescription" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateRecord">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex';
import axios from 'axios'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const records = ref([])
const dialogVisible = ref(false)
const editForm = reactive({
  failureRepairId: null as number | null,
  title: '',
  type: '',
  contactNumber: '',
  repairAddress: '',
  faultDescription: '',
  repairStatus: ''
})

const sortRecords = (records: any[]) => {
  return records.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())
}

const sortedPendingRecords = computed(() => {
  const pendingRecords = records.value.filter((record: any) => record.repairStatus === '申请中')
  return sortRecords(pendingRecords)
})

const sortedApprovedRecords = computed(() => {
  const approvedRecords = records.value.filter((record: any) => record.repairStatus !== '申请中')
  return sortRecords(approvedRecords)
})

const handleBack = () => {
  router.back()
}

const returnToMenu = () => {
  router.push('/home')
}

const store = useStore();

const fetchRecords = async () => {
  try {
    const user = store.getters.user;
    if (!user || !user.userNo) {
      ElMessage.error('用户未登录或用户信息不完整');
      return;
    }

    const response = await axios.get(`http://localhost:8001/failure-repair/select/${user.userNo}`);
    //const response = await axios.get(`http://localhost:8001/failure-repair/select/1046`);
    records.value = response.data;
  } catch (error) {
    console.error('Error fetching failure repair records:', error);
    ElMessage.error('获取报修记录失败');
  }
};

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

const editRecord = (record: any) => {
  Object.assign(editForm, record)
  dialogVisible.value = true
}

const updateRecord = async () => {
  try {
    const response = await axios.put(`http://localhost:8001/failure-repair/update`, editForm)
    if (response.data) {
      ElMessage.success('记录更新成功')
      dialogVisible.value = false
      fetchRecords() // 重新获取记录
    }
  } catch (error) {
    console.error('Error updating record:', error)
    ElMessage.error('更新记录失败')
  }
}

/*const deleteRecord = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    } as const)

    const response = await axios.delete(`http://localhost:8001/failure-repair/delete/${id}`)
    if (response.data) {
      ElMessage.success('记录删除成功')
      fetchRecords() // 重新获取记录
    }
  } catch (error) {
    if (error !== 'cancel') {  // 用户取消不算错误
      console.error('Error deleting record:', error)
      ElMessage.error('删除记录失败')
    }
  }
}*/

onMounted(() => {
  fetchRecords()
})
</script>

<style scoped>
.page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  font-family: Arial, sans-serif;
  background-color: #f0f2f5;
  padding-bottom: 60px; /* 为固定栏留出空间 */
}

.content {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.records-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 15px;
}

.record-card {
  background-color: white;
  border-radius: 4px;
  padding: 10px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.card-title {
  margin-top: 0;
  margin-bottom: 8px;
  color: #1a1a1a;
  font-size: 18px;
}

.card-content {
  flex-grow: 1;
  font-size: 14px;
}

.card-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  gap: 10px;
}

.card-actions .el-button {
  flex: 0 0 auto;
}

.card-content p {
  margin: 4px 0;
  color: #4a4a4a;
}

.card-content span {
  color: #1a1a1a;
  font-weight: bold;
}

.fixed-bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.fixed-bottom-bar .el-button {
  width: 80%;
  max-width: 300px;
}

.edit-dialog :deep(.el-dialog) {
  max-width: 500px;
}

.edit-dialog :deep(.el-dialog__body) {
  padding: 20px 30px;
}

.edit-form :deep(.el-form-item__content) {
  margin-left: 0 !important;
  width: 100%;
}

.edit-form :deep(.el-input),
.edit-form :deep(.el-select) {
  width: 100%;
}

.edit-form :deep(.el-textarea__inner) {
  min-height: 100px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

.no-records {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-bottom: 15px;
}
</style>